"""
Flask应用工厂模式
"""
from flask import Flask
from app.config import config_by_name
from app.extensions import db, jwt, cors, migrate


def create_app(config_name='development'):
    """创建Flask应用实例"""
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config_by_name[config_name])
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    cors.init_app(app)
    migrate.init_app(app, db)
    
    # 注册蓝图
    from app.blueprints.auth import auth_bp
    from app.blueprints.api import api_bp
    from app.blueprints.analytics import analytics_bp
    from app.blueprints.recommend import recommend_bp
    from app.blueprints.main import main_bp
    
    app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')
    app.register_blueprint(api_bp, url_prefix='/api/v1')
    app.register_blueprint(analytics_bp, url_prefix='/api/v1/analytics')
    app.register_blueprint(recommend_bp, url_prefix='/api/v1/recommendations')
    app.register_blueprint(main_bp)
    
    # 注册错误处理器
    register_error_handlers(app)
    
    # 注册请求钩子
    register_request_hooks(app)
    
    return app


def register_error_handlers(app):
    """注册全局错误处理器"""
    from flask import jsonify
    
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            'success': False,
            'error': 'Resource not found',
            'message': str(error)
        }), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({
            'success': False,
            'error': 'Internal server error',
            'message': str(error)
        }), 500
    
    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            'success': False,
            'error': 'Bad request',
            'message': str(error)
        }), 400
    
    @app.errorhandler(401)
    def unauthorized(error):
        return jsonify({
            'success': False,
            'error': 'Unauthorized',
            'message': 'Authentication required'
        }), 401
    
    @app.errorhandler(403)
    def forbidden(error):
        return jsonify({
            'success': False,
            'error': 'Forbidden',
            'message': 'You do not have permission to access this resource'
        }), 403


def register_request_hooks(app):
    """注册请求钩子"""
    import uuid
    from flask import g, request
    import logging
    
    logger = logging.getLogger(__name__)
    
    @app.before_request
    def before_request():
        """请求前处理"""
        g.request_id = str(uuid.uuid4())
        logger.info(f"Request {g.request_id}: {request.method} {request.path}")
    
    @app.after_request
    def after_request(response):
        """请求后处理"""
        response.headers['X-Request-ID'] = g.get('request_id', 'unknown')
        return response

